package com.example.javagobang.api;

import com.example.javagobang.constant.Constants;
import com.example.javagobang.game.MatchQueue;
import com.example.javagobang.game.OnlineUser;
import com.example.javagobang.model.MatchRequest;
import com.example.javagobang.model.MatchResponse;
import com.example.javagobang.model.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class MatchAPI extends TextWebSocketHandler {
    //处理json数据
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OnlineUser onlineUser;
    @Autowired
    private MatchQueue matchQuery;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            UserInfo userInfo =(UserInfo) session.getAttributes().get(Constants.user);

            if(onlineUser.getFromGameHall(userInfo.getUserId()) != null
                    || onlineUser.getFromGameRoom(userInfo.getUserId()) != null){
                MatchResponse matchResponse = new MatchResponse();
                matchResponse.setOk(true);
                matchResponse.setReason("禁止重复登录进入游戏");
                matchResponse.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
                session.close();
                return;
            }
            onlineUser.enterGameHall(userInfo.getUserId(),session);
            System.out.println("玩家" + userInfo.getUsername() + " 进入游戏大厅");
        }catch (NullPointerException e){
            e.printStackTrace();


           MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }


    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        UserInfo userInfo =(UserInfo) session.getAttributes().get(Constants.user);
        String payload = message.getPayload();
        MatchRequest request = objectMapper.readValue(payload,MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if(request.getMessage().equals("startMatch")){
            //进入匹配队列
            matchQuery.add(userInfo);
            response.setOk(true);
            response.setMessage("startMatch");

        }else if(request.getMessage().equals("stopMatch")){
            matchQuery.remove(userInfo);
            response.setOk(true);
            response.setMessage("stopMatch");
        }else {
            response.setOk(false);
            response.setReason("未知匹配请求");
        }
        String json = objectMapper.writeValueAsString(response);
        session.sendMessage(new TextMessage(json));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        try {
            UserInfo userInfo =(UserInfo) session.getAttributes().get(Constants.user);
            WebSocketSession tempSession = onlineUser.getFromGameHall(userInfo.getUserId());
            //如果此时拿到的原来的session等于websocket传入的session一样,才执行下线的操作
            if(tempSession == session){
                onlineUser.exitGameHall(userInfo.getUserId());
            }
            //异常断开，也要结束匹配
            matchQuery.remove(userInfo);
        }catch (NullPointerException e){
            e.printStackTrace();
            System.out.println("MatchAPI：用户未有登录");
          /*  MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));*/
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            UserInfo userInfo =(UserInfo) session.getAttributes().get(Constants.user);
            WebSocketSession tempSession = onlineUser.getFromGameHall(userInfo.getUserId());
            //如果此时拿到的原来的session等于websocket传入的session一样,才执行下线的操作
            if(tempSession == session){
                onlineUser.exitGameHall(userInfo.getUserId());
            }
            //正常断开结束匹配
            matchQuery.remove(userInfo);
        }catch (NullPointerException e){
            e.printStackTrace();
            //断开连接无法进行发送
            System.out.println("MatchAPI：用户未有登录");
          /*  MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));*/
        }

    }
}
